<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="报告类型" prop="reportType">
        <el-select v-model="queryParams.reportType" placeholder="请选择报告类型" clearable>
          <el-option v-for="item in reportTypeData" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上传人" prop="uploader">
        <el-input v-model="queryParams.uploader"></el-input>
      </el-form-item>
      <el-form-item label="上传日期" prop="uploadTime">
        <el-date-picker v-model="queryParams.uploadTime" type="daterange" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button plain icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="uploadTemp">上传</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableData" stripe>
      <el-table-column label="图件类型名称" align="center" prop="mapType" />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="报告类型" align="center" prop="reportType">
        <template #default="{row}">
          <span v-if="row.reportType == '0'">预评估报告</span>
          <span v-else-if="row.reportType == '1'">现场调查报告</span>
        </template>
      </el-table-column>
      <el-table-column label="版式" align="center" prop="format">
        <template #default="{row}">
          <span v-if="row.format == '0'">横版</span>
          <span v-else-if="row.format == '1'">竖版</span>
          <span v-else-if="row.format == '2'">无</span>
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="uploader" />
      <el-table-column label="上传日期" align="center" prop="uploadTime" />
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button type="text" @click="downloadTemp(row)">下载</el-button>
          <el-button type="text" @click="deleteTemp(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="queryParams.page"
      v-model:limit="queryParams.rows" @pagination="getList" />

    <el-dialog title="图件模板上传" v-model="tempUploadOpen" width="800px" append-to-body @open="initTemp" @close="close">
      <el-form ref="tempRef" :model="tempForm" :rules="tempRules" label-width="120px">
        <el-form-item label="报告类型" prop="reportType">
          <el-radio-group v-model="tempForm.reportType" class="ml-4" @change="getMapType">
            <el-radio label="0">预评估报告</el-radio>
            <el-radio label="1">现场调查报告</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="图件类型名称" prop="mapTypeId">
              <el-select v-model="tempForm.mapTypeId" @change="changeMapType">
                <el-option v-for="item in mapTypeData" :key="item.id" :label="item.mapType" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="tempForm.dictType">
            <el-form-item label="图件类型" prop="dictType">
              <el-input v-model="tempForm.dictType" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="tempForm.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="选择文件" prop="templateId">
          <el-input type="hidden" />
          <FileUpload ref="fileUpload" :fileType="['ult']" @beforeUpload="beforeUpload" @uploadSuccess="uploadSuccess" downloadUrl="/attachment/downLoad" uploadUrl="/attachment/uploadTemplate" v-model="tempForm.templateId"></FileUpload>
          <!-- <FileUpload ref="fileUpload" v-model="tempForm.templateId"></FileUpload> -->
        </el-form-item>
        <el-form-item label="版式" prop="format">
          <el-select v-model="tempForm.format">
            <el-option label="横版" value="0"></el-option>
            <el-option label="竖版" value="1"></el-option>
            <!--<el-option label="无" value="2"></el-option>-->
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { queryMapTemplates, getByReportType, saveMapTemplate, deleteMapTemplate } from '@/api/resultManag/chartTempManage'

const { proxy } = getCurrentInstance()
const data = reactive({
  queryParams: {
    page: 1,
    rows: 10,
    reportType: '',
    uploader: '',
    uploadTime: []
  },
  total: 0,
  reportTypeData: [
    { label: '预评估报告', value: '0' },
    { label: '现场调查报告', value: '1' },
  ],
  tableData: [],
  tempForm: {
    reportType: '0'
  }
})
const { queryParams, total, reportTypeData, tableData, tempForm } = toRefs(data)
const tempRules = ref({
  reportType: [{ required: true, message: '请选择报告类型！', trigger: 'change' }],
  mapTypeId: [{ required: true, message: '请填写图件类型！', trigger: 'change' }],
  templateId: [{ required: true, message: '请上传模板！', trigger: 'change' }],
  templateName: [{ required: true, message: '请填写模板名称！', trigger: 'blur' }],
  format: [{ required: true, message: '请填写版式！', trigger: 'change' }]
})
const showSearch = ref(true)
const loading = ref(false)
const tempUploadOpen = ref(false)
let mapTypeData = ref([])

// 分页
const getList = () => {
  loading.value = true
  queryMapTemplates({ ...queryParams.value, uploadTime: '' }).then(res => {
    if (res.code == 200) {
      tableData.value = res.data.rows
      total.value = res.data.total
    }
    loading.value = false
  }).catch(err => loading.value = false)
}

// 查询
const handleQuery = () => {
  let uploadTime = queryParams.value.uploadTime
  queryParams.value.startTime = uploadTime ? uploadTime[0] : "";
  queryParams.value.endTime = uploadTime ? uploadTime[1] : "";
  getList()
}

// 重置
const resetQuery = () => {
  proxy.resetForm("queryRef");
  queryParams.value.page = 1
  handleQuery();
}

// 下载
const downloadTemp = (row) => {
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoad?attachId="+ encodeURIComponent(row.templateId);
}

// 删除
const deleteTemp = (row) => {
  proxy.$modal.confirm(`是否确认删除${row.templateName}`).then(() => {
    return deleteMapTemplate(row.id)
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功！')
    getList()
  })
}

// 上传
const uploadTemp = () => {
  tempUploadOpen.value = true
}

const initTemp = () => {
  getMapType(tempForm.value.reportType)
}

// 根据报告类型获取图件类型
const getMapType = (val) => {
  getByReportType(val).then(res => {
    if (res.code == 200) {
      mapTypeData.value = res.data
    }
  })
}

// 图件类型选择
const changeMapType = (val) => {
  let curMapType = mapTypeData.value.find(item => item.id == val)
  tempForm.value.mapType = curMapType.mapType
  tempForm.value.enableFlag = curMapType.enableFlag
  tempForm.value.dictCode = curMapType.dictCode
  tempForm.value.dictType = curMapType.dictType
}

// 保存
const submitForm = () => {
  let fileList = proxy.$refs["fileUpload"].fileList
  let newTemplateId = ''
  if(fileList.length>0){
    // tempForm.value.templateId = fileList.map(item => item.attachId).join(',')
    tempForm.value.templateId = fileList
    newTemplateId = fileList.map(item => item.attachId).join(',')
  }
  
  let newTemplateName = ''
  if(tempForm.value.format == '0'){
    newTemplateName = tempForm.value.templateName + '（横板）'
  }else if(tempForm.value.format == '1'){
    newTemplateName = tempForm.value.templateName + '（竖版）'
  }
  let params = {
    ...tempForm.value,
    templateName: newTemplateName,
    templateId: newTemplateId
  }
  console.log(tempForm.value)
  proxy.$refs.tempRef.validate((valid, fields) => {
    if (valid) {
      saveMapTemplate(params).then(res => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('保存成功！')
          getList()
        }
        tempUploadOpen.value = false
      }).catch(err => tempUploadOpen.value = false)
    } else {
      proxy.$refs.tempRef.scrollToField(Object.keys(fields)[0])
    }
  })
}

// 关闭弹框
const close = () => {
  proxy.resetForm('tempRef')
  tempForm.value.templateId = ''
}

const beforeUpload = (file, cb) => {
  let reg = /[\u4E00-\u9FA5]/g
  if(reg.test(file.name)){
    proxy.$modal.msgError(`上传文件名称不能包含中文!`);
    cb(false)
  }
}
const uploadSuccess = () => {
  proxy.$refs.tempRef.clearValidate('templateId')
}

onMounted(() => {
  getList()
})
</script>